package com.itheima.tilas.filter;

import com.alibaba.fastjson.JSONObject;
import com.itheima.tilas.Utils.JwtUtil;
import com.itheima.tilas.Utils.ResultUtil;
import com.itheima.tilas.entity.Emp;
import com.itheima.tilas.mapper.EmpMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;

/**
 * 登录过滤器,进行登录token拦截
 * //@Component
 * @author 123
 */
@Slf4j
//@Component
public class LoginFilter implements Filter {
    @Resource
    EmpMapper empMapper;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //初始化过滤器
        Filter.super.init(filterConfig);
        log.info("初始化过滤器");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //执行过滤
        log.info("开始执行http请求过滤");
        //参数向下转型成HttpServletRequest 以及HttpServletResponse
        HttpServletRequest servletRequest = (HttpServletRequest) request;
        HttpServletResponse servletResponse = (HttpServletResponse) response;
        //放行登录接口
        String requestUri = servletRequest.getRequestURI();
        if (requestUri.contains("login")) {
            chain.doFilter(servletRequest, servletResponse);
            return;
        }
        //获取请求头中的token
        String token = servletRequest.getHeader("token");
        if (Objects.isNull(token)) {
            writeErrorResponse(servletResponse, "请先登录");
            return;
        }
        //TODO 使用jwt工具类验证token是否正确
        try {
            JSONObject jsonObject = JwtUtil.verifyToken(token);
            Emp emp = empMapper.selectEmpByUsername(jsonObject.getString("username"));
            if (Objects.isNull(emp) || !emp.getPassword().equals(jsonObject.getString("password"))) {
                writeErrorResponse(servletResponse, "Token不合法或者已过期");
                return;
            }
        } catch (Exception e) {
            writeErrorResponse(servletResponse, "Token不合法或者已过期");
            return;
        }
        //过滤链对象执行完过滤逻辑之后放行http请求,把request重新交给 Controller(servlet)
        chain.doFilter(request, response);
        log.info("过滤完成");
    }

    private static void writeErrorResponse(HttpServletResponse servletResponse, String msg) throws IOException {
        //设置UTF-8编码
        servletResponse.setContentType("application/json; charset=UTF-8");
        servletResponse.setCharacterEncoding("UTF-8");
        //设置状态码
        //import org.apache.http.HttpStatus apache下的包
        //servletResponse.setStatus(HttpStatus.SC_UNAUTHORIZED)
        //import org.springframework.http.HttpStatus springBoot下的状态码包
        servletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
        PrintWriter writer = servletResponse.getWriter();
        ResultUtil fail = ResultUtil.fail(msg);
        //使用fastJson 把对象转成json字符串
        writer.write(JSONObject.toJSONString(fail));
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
